﻿using LitJson;
using LNet;
using OestsCommon.Model;
using OestsDataBase;
using OestsServer.Net;
using OSESServer;
using System.Collections.Generic;
using System.Linq;

namespace OestsServer.Handlers.OESPHandlers
{

    public class SubjectTableHandler : HandlerBase<OESPClientChannel>
    {
        public override PacketKey PKey => PacketKey.SubjectTable;

        public override void Execute(OESPClientChannel client, Request packet)
        {
            base.Execute(client, packet);

            List<Subject> list = SubjectDAL.GetSubjectData();
            int group = list.Count / 500;
            int remain = list.Count % 500;
            if (remain > 0)
                group++;
            List<List<Subject>> splitList = Tool.SpiltList(list, group);

            splitList.ForEach(s =>
            {
                ResponsePacket.DataObject = s;
                client.Send(ResponsePacket);
            });



        }
    }


    public class AddSubjectHandler : HandlerBase<OESPClientChannel>
    {
        public override PacketKey PKey => PacketKey.AddSubject;
        public override void Execute(OESPClientChannel client, Request resquestPacket)
        {
            base.Execute(client, resquestPacket);

            List<Subject> list = JsonMapper.ToObject<List<Subject>>(resquestPacket.DataStr);
            list.ForEach(s => s.Id = SubjectDAL.AddSubject(s));
            ResponsePacket.DataObject = list;
            client.Send(ResponsePacket);
        }
    }

    public class DeleteSubjectHandler : HandlerBase<OESPClientChannel>
    {
        public override PacketKey PKey => PacketKey.DeleteSubject;

        public override void Execute(OESPClientChannel client, Request resquestPacket)
        {
            base.Execute(client, resquestPacket);

            //读取数据库
            List<int> list = JsonMapper.ToObject<List<int>>(resquestPacket.DataStr);
            List<int> bakc = list.Where(i => SubjectDAL.Delete(i)).ToList();//TODO::删除试卷中包含的题目未做处理
            ResponsePacket.DataObject = bakc;
            client.Send(ResponsePacket);
        }
    }

    public class ModifySubjectHandler : HandlerBase<OESPClientChannel>
    {
        public override PacketKey PKey => PacketKey.ModifySubject;

        public override void Execute(OESPClientChannel client, Request resquestPacket)
        {
            base.Execute(client, resquestPacket);
            ResponsePacket = new Response(resquestPacket);
            Subject subject = JsonMapper.ToObject<Subject>(resquestPacket.DataStr);
            if (SubjectDAL.Modify(subject))
            {
                ResponsePacket.DataObject = subject;
                ResponsePacket.ReturnCode = ReturnCode.Success;
                //client.Send(ResponsePacket);
            }
            else
            {
                ResponsePacket.ReturnCode = ReturnCode.Fail;
                ResponsePacket.RetrunMessage = "修改题目失败！";

            }
            client.Send(ResponsePacket);


        }
    }
}